package chain

import (
	"fmt"
	"math/rand"
)

var flag = false
var data = make(map[int]bool)

//var sg = sync.WaitGroup{}

func Test_pipline() {
	wg.Add(1)
	a := make(chan int)
	b := make(chan int)
	go sendNum(50, 10, a)
	go recive(a, b)

	sum(b)

}

func sum(b chan int) int {
	sum := 0
	for v := range b {
		sum += v
	}
	fmt.Println("sum is", sum)
	return sum
}

func recive(a chan int, b chan int) {
	for r := range a {
		_, ok := data[r]
		if ok {
			fmt.Println("Data is duplicated ", r)
			flag = true
		} else {
			data[r] = true
			b <- r
		}
	}
	close(b)
}

func sendNum(max int, min int, out chan<- int) {
	for {
		if flag {
			close(out)
			fmt.Println("sendNum is close")
			return
		}
		num := generateNum(max, min)
		out <- num
		fmt.Println("send num ", num)
	}
}

func generateNum(max int, min int) int {
	return rand.Intn(max-min) + min
}
